package io.web.gateway.filter;

import io.web.gateway.rpc.AdminService;
import io.web.utils.Constant;
import io.web.utils.SignUtils;
import io.web.gateway.utils.ResponseHandler;
import io.web.vo.interfaceinfo.User;
import io.web.vo.interfaceinfo.UserAccessRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.BitSet;

/**
 * AuthGlobalFilter.
 * 鉴权
 *
 * @date 2023-05-30
 */
@Component
@Slf4j
@AllArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final BitSet bitSet = new BitSet();

    private final AdminService adminService;

    /**
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String nonce = headers.getFirst("nonce");
        String timestamp = headers.getFirst("timestamp");
        String sign = headers.getFirst("sign");
        String content = headers.getFirst("data");

        if (accessKey == null) {
            return ResponseHandler.unauthorized(exchange);
        }

        UserAccessRequest userAccessRequest = new UserAccessRequest();
        userAccessRequest.setAccessKey(accessKey);
        User user = adminService.getUserByAccessKey(userAccessRequest);

        if (user == null || user.getSercetKey() == null) {
            return ResponseHandler.unauthorized(exchange);
        }

        if (nonce == null) {
            return ResponseHandler.unauthorized(exchange);
        }

        if (timestamp == null || System.currentTimeMillis() - Long.parseLong(timestamp) > 5 * 60 * 1000) {
            return ResponseHandler.unauthorized(exchange);
        }

        // 验证
        if (content == null || sign == null
                || !SignUtils.verify(content, sign, user.getSercetKey())) {
            return ResponseHandler.unauthorized(exchange);
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 200;
    }
}
